package com.kara.woodAgent.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author tzy
 * @version 1.0
 * @project wood_agent
 * @description
 * @date 2025/6/7 16:12:20
 */

@Configuration
@Slf4j
public class SaTokenConfig implements WebMvcConfigurer {

	@Bean
	public CorsFilter corsFilter(){
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.setAllowedOrigins(List.of("*")); // 设置允许的来源
		corsConfiguration.setAllowedMethods(List.of("*"));     // 设置允许的方法
		corsConfiguration.setAllowedHeaders(List.of("*"));     // 设置允许的头部
		corsConfiguration.setAllowCredentials(true); // 允许携带凭证

		UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
		urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

		return new CorsFilter(urlBasedCorsConfigurationSource);
	}


	// 注册 Sa-Token 拦截器
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new SaInterceptor(handle -> {
					// 登录拦截，放行白名单
					SaRouter.match("/**").notMatch(
							List.of(
									"/user/login",
									"/user/register",
									"/upload/**"
							)
					).check(r -> StpUtil.checkLogin());

				}))
				.addPathPatterns("/**");
	}


}
